'use strict';

const Service = require('egg').Service;

class ArticleService extends Service {

  // 新增
  async createArticle(Article) {
    const { app } = this;
    return await app.model.Article.create(Article);
  }

  /**
   *获取列表 带用户搜索记录
   * @param {载荷} payload
   * @return {Promise<>}
   */
  async getArticle(payload) {
    const { app, ctx } = this;
    const Op = app.Sequelize.Op;
    const { pageNum, pageSize, category_id, user_id, status, keywords, begin_pubdate, end_pubdate } = payload;
    const where = {};
    if (category_id) { where.category_id = category_id; }
    if (user_id) { where.user_id = user_id; }
    if (status) { where.status = status; }
    if (keywords) {
      where.title = { [Op.like]: `%${keywords}%` };
    }
    if (begin_pubdate && end_pubdate) {
      where.createdAt = { [Op.between]: [ begin_pubdate, end_pubdate ] };
    }// 查询这个字段-xx之间  }
    // notBetween
    try {
      const { count, rows } = await app.model.Article.findAndCountAll({
        where,
        // attributes: [ 'id', 'title', 'createdAt', 'category_id', 'status' ], // 只查哪些字段
        order: [[ 'createdAt', 'desc' ]], // 根据创建时间倒序排序
        include: [
          {
            model: this.app.model.ArticleCategory,
            as: 'category',
            attributes: [ 'name' ], // 只显示哪些字段
            // through: { attributes: [] }, // 排除中间表
          },
          {
            model: this.app.model.User,
            as: 'user',
            attributes: [ 'user_name', 'avatar' ], // 只显示哪些字段
            // through: { attributes: [] }, // 排除中间表
          },
        ],
        offset: (pageNum - 1) * pageSize,
        limit: pageSize * 1,
      });
      return {
        pageNum,
        pageSize,
        total: count,
        list: rows,
      };
    } catch (error) {
      console.error(error);
      return null;
    }
  }

  // 删除
  // async delArticle(id) {
  //   const { app } = this;
  //   return await app.model.Article.destroy({ where: { id } });
  // }
  async del(payload) {
    const { app } = this;
    return await app.model.Article.destroy({ where: { id: payload.ids } });
  }

  // 修改
  async updateArticle(id, category) {
    const { app } = this;
    return await app.model.Article.update(category, { where: { id } });
  }

  // 根据id获取信息
  async getInfo(id) {
    const { app, ctx } = this;
    const res = await app.model.Article.findOne(
      {
        where: { id },
        include: {
          model: this.app.model.User,
          as: 'user',
          attributes: [ 'user_name', 'avatar' ], // 只显示哪些字段
        // through: { attributes: [] }, // 排除中间表
        },
      });
    if (res.dataValues) {
      // 查询成功的话 就让阅读量加1
      await app.model.Article.increment('read_count', { where: { id } });
      // 获取文章详情信息成功的话就新增一条用户查看 浏览记录
      await ctx.service.admin.articleView.createUserView(id);

    }
    return res.dataValues;
  }

}

module.exports = ArticleService;
